#include "../apue.h"

int main (void) {
	int fd[2];
	pid_t pid;
	int n;
	char line[MAXLINE];

	if (pipe(fd) < 0) {
		err_sys("pipe error");
	}
	if ((pid = fork()) < 0) {
		err_sys("fork error");
	} else if (pid > 0) {
		close(fd[0]);
		if (fd[1] != STDOUT_FILENO) {
			if (dup2(fd[1],STDOUT_FILENO) != STDOUT_FILENO)
				err_sys("dup2 error to STDOUT");
			close(fd[1]);
		}
		write(STDOUT_FILENO, "hello world\n", 12);
	} else {
		close(fd[1]);
		if (fd[0] != STDIN_FILENO) {
			if (dup2(fd[0],STDIN_FILENO) != STDIN_FILENO)
				err_sys("dup2 error to STDIN");
			close(fd[0]);
		}
		n = read(STDIN_FILENO, line, MAXLINE);
		write(STDOUT_FILENO, line, n);
	}
	exit(0);
}
